package com.lightsaber.trade.monitorclient.service.device;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springside.modules.utils.spring.SpringContextHolder;

import com.lightsaber.trade.cloth.ws.api.device.ViewCommand;
import com.lightsaber.trade.monitorclient.constants.AppConstant;

@Service
public class ViewCommandClientManager implements Runnable {

    final static Logger LOG = LoggerFactory.getLogger(ViewCommandClientManager.class);

    @Value(value = "#{appProperties['device.serial.number']}")
    private String deviceSerialNumber;

    public void reportStatus(String content) {
        ViewCommand viewCommand = SpringContextHolder.getBean("viewCommand");

        String re = viewCommand.collectInfo(deviceSerialNumber, content);

        LOG.debug("{}'s info send sucessfully.", deviceSerialNumber);
    }

    @Override
    public void run() {
        String input = "";

        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);

        try {
            // ----------input your content on you keyboard---------START
            while (!StringUtils.equals(input, AppConstant.THREAD_EXIT)) {

                if (StringUtils.isNotBlank(input)) {
                    this.reportStatus(input);
                }

                try {
                    input = br.readLine();
                } catch (IOException e) {
                    LOG.error(e.toString());
                }

            }
            // ----------input your content on you keyboard---------END

        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        } finally {
            try {
                br.close();
                isr.close();
                LOG.info("Device client shut down successfully......");
            } catch (IOException e) {
                LOG.error(e.getMessage(), e);
            }
        }

        System.exit(0);

    }
}
